package com.gaga.console.core.service.impl.multimodel;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gaga.common.constant.BvConstants;
import com.gaga.common.enums.SingleDoubleModelType;
import com.gaga.console.base.utils.MyStringUtil;
import com.gaga.console.base.utils.RestUtils;
import com.gaga.console.core.entity.SysConfig;
import com.gaga.console.core.entity.result.GptResult;
import com.gaga.console.core.service.SysConfigService;
import com.gaga.console.core.service.impl.multimodel.result.SwitchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;

/**
 * @author liujia
 * @version 1.0
 * @date 2025/4/9-10:03
 */
@Slf4j
public abstract class AbstractModelHandler implements ModelHandler {

    protected SysConfigService sysConfigService;
    protected String modelPath;
    protected String sovitsUrl;
    protected String gptUrl;
    protected SingleDoubleModelType singleDoubleModelType;

    protected void init(SysConfigService sysConfigService, String modelPath, String sovitsUrl, String gptUrl, SingleDoubleModelType singleDoubleModelType) {
        this.sysConfigService = sysConfigService;
        this.modelPath = modelPath;
        this.gptUrl = gptUrl;
        this.sovitsUrl = sovitsUrl;
        this.singleDoubleModelType = singleDoubleModelType;
    }

    /**
     * 构建提示词
     *
     * @return
     */
    @Override
    public SwitchResult switchCkpt(File[] files, String modelName) {
        SwitchResult switchResult = new SwitchResult();
        //调用两个接口切换模型
        Optional<File> ckptFileOption = Arrays.stream(files)
                .filter(file -> file.getName().contains(modelName) && MyStringUtil.endsWithIgnoreCase(file.getName(), "ckpt")).findFirst();
        if (ckptFileOption.isPresent()) {
            String ckptUrl = gptUrl.replace("port", getRealPort());
            //接口1
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("gpt_path", modelPath + File.separator + modelName + File.separator + ckptFileOption.get().getName());

            String respStr = RestUtils.post(ckptUrl, jsonObject.toJSONString());

            GptResult gptResult = JSONObject.parseObject(respStr, GptResult.class);
            if (StringUtils.isBlank(gptResult.getMessage()) || !"success".equals(gptResult.getStatus())) {
                switchResult.setIsSuceess(false);
                return switchResult;
            }
            switchResult.setIsSuceess(true);
        }
        return switchResult;
    }

    /**
     * 构建提示词
     *
     * @return
     */
    @Override
    public SwitchResult switchPth(File[] files, String modelName) {
        SwitchResult switchResult = new SwitchResult();
        //调用两个接口切换模型
        Optional<File> pthFileOption = Arrays.stream(files)
                .filter(file -> file.getName().contains(modelName) && MyStringUtil.endsWithIgnoreCase(file.getName(), "pth")).findFirst();
        if (pthFileOption.isPresent()) {
            String pthUrl = sovitsUrl.replace("port", getRealPort());
            //接口2
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sovits_path", modelPath + File.separator + modelName + File.separator + pthFileOption.get().getName());
            jsonObject.put("prompt_language", "中文");
            jsonObject.put("text_language", "中文");

            String respStr = RestUtils.post(pthUrl, jsonObject.toJSONString());

            if (StringUtils.isBlank(respStr)) {
                switchResult.setIsSuceess(false);
                return switchResult;
            }

            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode rootNode = mapper.readTree(respStr);
                if (rootNode == null) {
                    log.error("pth切换成功");
                    switchResult.setIsSuceess(false);
                }
                if (rootNode.isArray()) {
                    switchResult.setIsSuceess(true);
                    log.error("pth切换成功");
                } else if (rootNode.isObject()) {
                    switchResult.setIsSuceess(false);
                } else {
                    log.error("pth切换成功");
                    switchResult.setIsSuceess(false);
                }
            } catch (JsonProcessingException e) {
                log.error("pth切换成功");
                switchResult.setIsSuceess(false);
            }

        }
        return switchResult;
    }

    @Override
    public void updateRefAudioPath(File[] files, String modelName) {
        Optional<File> wavFileOption = Arrays.stream(files).filter(file -> MyStringUtil.endsWithIgnoreCase(file.getName(), "wav")).findFirst();
        if (wavFileOption.isPresent()) {
            UpdateWrapper<SysConfig> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(BvConstants.CONFIG_KEY, getRefAudioPathKey())
                    .set(BvConstants.CONFIG_VALUE, modelPath + File.separator + modelName + File.separator + wavFileOption.get().getName());
            sysConfigService.update(updateWrapper);
        }
    }

    @Override
    public void updatePromptText(File[] files, String modelName) {
        Optional<File> txtFileOption = Arrays.stream(files).filter(file -> MyStringUtil.endsWithIgnoreCase(file.getName(), "txt")).findFirst();
        if (txtFileOption.isPresent()) {
            try {
                String content = FileUtils.readFileToString(txtFileOption.get());

                UpdateWrapper<SysConfig> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq(BvConstants.CONFIG_KEY, getPromptTextKey())
                        .set(BvConstants.CONFIG_VALUE, content);
                sysConfigService.update(updateWrapper);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void updateCurrentModel(String modelName) {
        UpdateWrapper<SysConfig> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(BvConstants.CONFIG_KEY, getCurrentModelKey())
                .set(BvConstants.CONFIG_VALUE, modelName);
        sysConfigService.update(updateWrapper);
    }
}
